﻿using System.Text;
using Newtonsoft.Json;

namespace Common;

/// <summary>
/// json序列化和反序列化帮助类
/// </summary>
public class JsonHelper
{
    // 抽一个类出来  钥匙以后换了组件 直接在这边换就好了

    /// <summary>
    /// Obj To Json
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string SerializeObject(object? obj)
    {
        if (obj==null)
        {
            return string.Empty;
        }
        return JsonConvert.SerializeObject(obj);
    }
    /// <summary>
    /// Json To  Obj
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T DeserializeObject<T>(string json)
    {
        if (string.IsNullOrWhiteSpace(json))
        {
            return default;
        }
        return JsonConvert.DeserializeObject<T>(json);
    }
    /// <summary>
    /// 将对象序列化成
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static byte[] SerializeToUtf8Bytes(object obj)
    {
        var json = SerializeObject(obj);
        return Encoding.UTF8.GetBytes(json);
    }
}